<template>
  <Dialog
    v-model="dialogVisible"
    width="600px"
    title="上传退款凭证"
    :before-close="() => closeDialog(formRef)"
  >
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="110px">
      <div class="w-full flex justify-between">
        <div class="w-80%">
          <el-form-item :label="t('orderReturn.orderUpload')" prop="voucher_id">
            <div class="flex flex-items-center">
              <UploadFile
                url="/common/uploadFile"
                ref="UploadFileRef"
                upload-file-button-name="上传凭证"
                :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'word', 'txt']"
                :params="{ directory: 6 }"
                :limit="1"
                list-type="picture"
                :show-file-list="true"
                @upload-success-res="handleUploadCallback"
                @handle-remove-file="handleRemoveFile"
                @handle-picture-card-preview="handlePictureCardPreview"
              />
            </div>
          </el-form-item>
          <el-form-item :label="t('orderReturn.return_price')" prop="return_price">
            <el-input
              v-model="form.return_price"
              clearable
              type="number"
              :placeholder="t('orderReturn.return_price')"
              style="width: 250px"
            />
          </el-form-item>
          <el-form-item :label="t('orderReturn.notes')" prop="notes">
            <el-input
              v-model="form.notes"
              type="textarea"
              :autosize="{ minRows: 10, maxRows: 15 }"
              :placeholder="t('orderReturn.notes')"
            />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)"
        >{{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit(formRef)">{{ t('common.ok') }} </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from 'element-plus'
import { uploadPaymentApi } from '@/api/order/pay'
import UploadFile from '@/components/UploadFile/index.vue'
import { createImageViewer } from '@/components/ImageViewer'
import { uploadFileApi } from '@/api/orderReturn'
const { push } = useRouter()

const emit = defineEmits(['refresh'])

const { t } = useI18n()

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  order_id: '',
  return_price: '',
  notes: ''
})

const rowDetail = ref<Record<string, any>>()

const rules = ref<FormRules>({
  return_price: [
    {
      required: true,
      message: t('orderReturn.return_priceMsg'),
      trigger: 'blur'
    }
  ],
  voucher_id: [
    {
      required: true,
      message: t('orderReturn.voucherIdMsg'),
      trigger: 'blur'
    }
  ]
})

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  form.value.voucher_id = val.id
}

const handleRemoveFile = (val: any) => {
  if (form.value.att_path && form.value.att_path.length) {
    form.value.att_path = form.value.att_path.filter(
      (item: Record<string, any>) => item.uploadFile.uid !== val.uid
    )
  }
}

const handlePictureCardPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val]
  })
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (!form.value.voucher_id) {
      ElMessage.error('请上传退款凭证')
      return
    }
    if (valid) {
      ElMessageBox.confirm('退款凭证确认之后无法修改，请谨慎操作', t('purchase.logistics.tips'), {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const resp = await uploadFileApi({
            id: form.value.order_id,
            voucher_id: form.value.voucher_id,
            amount: form.value.return_price,
            notes: form.value.notes
          })
          if (resp.code === 0) {
            ElMessage.success(t('orderReturn.uploadSucMsg'))
            closeDialog(formEl)
            emit('refresh')
          }
        })
        .catch(() => {})
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    order_id: '',
    return_price: '',
    notes: ''
  }
  formEl.resetFields()
  dialogVisible.value = false
}

const getBackShow = async (row: Record<string, any>) => {
  form.value.order_id = row.id
  rowDetail.value = row
}

defineExpose({
  dialogVisible,
  getBackShow
})
</script>
<style lang="less" scoped></style>
